# sql_copy.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net
#
package CCN::sql_copy::CCN;
use base qw(CCN::sql_copy);

sub initialize_sqlite3($$)
{
    my $sqlite3_file = shift;
    my $sql_file     = shift;

    unlink $sqlite3_file or die "unlink $sqlite3_file: $!"
        if -e $sqlite3_file;
    CCN::Scripting::exec_command("/usr/bin/sqlite3 '$sqlite3_file' < '$sql_file'");
    return local_sqlite3($sqlite3_file);
}

sub initialize_mysql($$)
{
    my $mysql_dbname = shift;
    my $sql_file     = shift;

    CCN::Scripting::exec_command(CCN::Scripting::sql::SQL_FILE($mysql_dbname,$sql_file));
    return local_mysql($mysql_dbname);
}

sub copy($$$$)
{
    our $db_from = shift; # a CCN::Database instance used as data source
    our $db_to   = shift; # a CCN::Database instance used as data destination
    my  $sql_file = shift; # the SQL definition file used as schema source
    my  $version  = shift; # a version identifier for this db copy

    # Open sql file and copy tables one by one
    open(my $fh,'<',$sql_file) or die "open($sql_file): $!";

    while(<$fh>)
    {
        if( /^\s*CREATE\s+TABLE\s+"?(\w+)"?/ )
        {
            my $table = $1;
            my $query_from = qq(SELECT * FROM "$table");
            __copy_table($db_from,$db_to,$table,$query_from);
            next;
        }
    }
    close($fh);

    __set_version($db_to,$version);
}

1;